package com.second.app.future;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.*;

/**
 * @Author GYZ
 * <pre>
 *  线程池结合futureTask处理多任务
 * </pre>
 */
public class MainDemo {
    public static void main(String[] args) {
        ThreadPoolExecutor threadPoolExecutor = new ThreadPoolExecutor(10, 20, 0, TimeUnit.MICROSECONDS, new LinkedBlockingDeque<>(), Executors.defaultThreadFactory());
        List<Future<Exception>> taskList = new ArrayList<>();
        for (int i = 0; i < 10; i++) {
            FutureTask<Exception> futureTask = new FutureTask<>(new Callable<Exception>() {
                @Override
                public Exception call() throws Exception {
                    for (int j = 0; j < 10; j++) {
                        System.out.println("线程：" + Thread.currentThread().getName() + ",打印j的值：" + (j + 1));
                        int  a = 1/0;
                    }
                    return null;
                }
            });
            threadPoolExecutor.submit(futureTask);
            taskList.add(futureTask);
        }

        try {
            for (Future<Exception> exceptionFuture : taskList) {
                Exception e = exceptionFuture.get();
                System.out.println("出现异常：" + e.getMessage());
            }
        } catch (InterruptedException e) {
            e.printStackTrace();
            System.out.println("任务没有执行：" + e.getMessage());
        } catch (ExecutionException e) {
            e.printStackTrace();
            System.out.println("线程id:"+Thread.currentThread().getName()+",任务执行出现异常：" + e.getMessage());
        }
    }
}
